package com.qmo.edu.moudle.activity;

import android.Manifest;
import android.os.Bundle;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.qmo.edu.moudle.fragment.FiveFragment;
import com.qmo.edu.moudle.fragment.ThreeFragment;
import com.qmo.edu.moudle.fragment.FourFragment;
import com.qmo.edu.moudle.fragment.OneFragment;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.beta.Beta;
import com.qmo.edu.R;
import com.qmo.edu.base.BaseMvpActivity;
import com.qmo.edu.base.BaseMvpFragment;
import com.qmo.edu.moudle.fragment.TwoFragment;
import com.qmo.edu.mvp.factroy.CreatePresenterAnnotation;
import com.qmo.edu.mvp.presenter.MainPresenter;
import com.qmo.edu.mvp.view.MainView;
import com.qmo.edu.utils.BottomNavigationViewHelper;
import com.qmo.edu.utils.FunctionUtils;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.ObservableTransformer;
import me.jessyan.autosize.utils.LogUtils;

@CreatePresenterAnnotation(MainPresenter.class)
public class MainActivity extends BaseMvpActivity<MainView, MainPresenter> implements MainView {
    @BindView(R.id.navigation)
    BottomNavigationView mNavigation;
    @BindView(R.id.fragment_container)
    FrameLayout mFragmentContainer;

    private ArrayList<BaseMvpFragment> mFragments;
    private Fragment mCurrentFragment;

    @Override
    public int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData() {
        initPermision();
        BottomNavigationViewHelper.disableShiftMode(mNavigation);
        mNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        mNavigation.setItemIconTintList(null);

    }

    private void initFragment(Bundle savedInstanceState) {
        mFragments = new ArrayList<>();


        if (savedInstanceState == null) {


            OneFragment oneFragment = new OneFragment();
            TwoFragment twoFragment = new TwoFragment();
            ThreeFragment threeFragment = new ThreeFragment();
            FourFragment fourFragment = new FourFragment();
            FiveFragment fiveFragment = new FiveFragment();


            mFragments.add(oneFragment);
            mFragments.add(twoFragment);
            mFragments.add(threeFragment);
            mFragments.add(fourFragment);
            mFragments.add(fiveFragment);
            addFragment(mFragments.get(0), R.id.fragment_container);
            mCurrentFragment = oneFragment;
            mNavigation.setSelectedItemId(R.id.one);
        }

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        initFragment(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FunctionUtils.fixInputMethodManagerLeak(MainActivity.this);
    }


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = item -> {
        switch (item.getItemId()) {

            case R.id.one:
                switchFragment(0);
                return true;
            case R.id.two:
                switchFragment(1);
                return true;
            case R.id.three:
                switchFragment(2);
                return true;
            case R.id.four:
                switchFragment(3);
                return true;
            case R.id.five:
                switchFragment(4);
                return true;

        }
        return false;
    };
    private long mExitTime;

    private void initPermision() {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE};
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.requestEach(permissions)
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        //result.agree(permission);
                        LogUtils.e("----------------获取权限");
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        //result.refuse(permission);
                        LogUtils.e("----------------拒绝,下次继续请求");
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』，提醒用户手动打开权限
                        //result.noMoreQuestions(permission);
                        LogUtils.e("----------------拒绝,不再询问");
                        Toast.makeText(this, "获取相机和读写权限被拒绝,请前往设置手动开启", Toast.LENGTH_SHORT).show();
                    }
                });

        Beta.checkUpgrade(false, false);
        if (Beta.getUpgradeInfo() != null) {
            LogUtils.e("--apkurl" + Beta.getUpgradeInfo().apkUrl);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 绑定物理返回键
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            // 如果两次按键时间间隔大于2000毫秒，则不退出
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                // 记录exitTime
                mExitTime = System.currentTimeMillis();
            } else {
                // 否则退出程序
                finish();
//                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void switchFragment(int position) {
        if (mFragments == null || mFragments.size() == 0) {
            initFragment(null);
        }


        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = mFragments.get(position);

        if (!fragment.isAdded() && getSupportFragmentManager().findFragmentByTag(fragment.getClass().getName()) == null) {

            transaction.hide(mCurrentFragment)
                    .add(R.id.fragment_container, fragment, fragment.getClass().getName())
                    .show(fragment)
                    .commit();

        } else {
            if (mCurrentFragment != fragment) {
                transaction.hide(mCurrentFragment).show(fragment).commit();
            }
        }
        mCurrentFragment = fragment;

    }

    @Override
    public <T> ObservableTransformer<T, T> bindLifeycle() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

}
